/**
 * @Author : JiGuangJie
 * @Date : 2022/9/20
 * @Time : 16:08
 * @Version : 1.0.0
 * @Description :
 */
window.onload = () => {
    // marker source 点数据源
    const markerSource = new ol.source.Vector({
        wrapX: false
    });
    // marker layer 点图层
    const markerLayer = new ol.layer.Vector({
        source: markerSource
    });

    const map = new ol.Map({
        layers: [
            new ol.layer.Tile({
                source: new ol.source.OSM()
            }),
            markerLayer
        ],
        target: 'map',
        view: new ol.View({
            center: [0, 0],
            zoom: 2
        })
    });

    const clear = () => {
        markerSource.clear();
    };

    document.getElementById('draw-marker').addEventListener('click', evt => {
        console.log('绘制Marker');
        clear();
        fetch('./data/marker.json').then(response => response.json()).then(res => {
            console.log(res);
            const {point, offset, url} = res;
            const iconFeature = new ol.Feature({
                geometry: new ol.geom.Point(point)
            });

            const iconStyle = new ol.style.Style({
                image: new ol.style.Icon({
                    anchor: offset,
                    anchorXUnits: 'pixels',
                    anchorYUnits: 'pixels',
                    src: url
                })
            });
            iconFeature.setStyle(iconStyle);

            markerSource.addFeature(iconFeature);

            const metersPerUnit = map.getView().getProjection().getMetersPerUnit();
            const realRadius = 100000 / metersPerUnit;

            const circleFeature = new ol.Feature({
                geometry: new ol.geom.Circle(point, realRadius * 1.145)
            });

            markerSource.addFeature(circleFeature);
        });
    });

    document.getElementById('draw-marker-offset').addEventListener('click', evt => {
        clear();
        fetch('./data/marker-offset.json').then(response => response.json()).then(res => {
            console.log(res);
            const {point, offset, url} = res;
            const iconFeature = new ol.Feature({
                geometry: new ol.geom.Point(point)
            });

            const iconStyle = new ol.style.Style({
                image: new ol.style.Icon({
                    anchor: offset,
                    anchorXUnits: 'pixels',
                    anchorYUnits: 'pixels',
                    src: url
                })
            });
            iconFeature.setStyle(iconStyle);

            markerSource.addFeature(iconFeature);

            const metersPerUnit = map.getView().getProjection().getMetersPerUnit();
            const realRadius = 100000 / metersPerUnit;

            const circleFeature = new ol.Feature({
                geometry: new ol.geom.Circle(point, realRadius * 1.145)
            });

            markerSource.addFeature(circleFeature);
        });
    });
};